package ebiz.buddhist.texts.data;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import ebiz.buddhist.texts.R;
  
public class DownItemAdapter extends BaseAdapter {
	Context maincon;
	LayoutInflater Inflater;
	ArrayList<DownItemList> arSrc;
	String[] mpFile = {
			"heartsutra","beopseong","hwaeom","chunsu",
			"sinju",/*"kanmu","bodalbomun","kanja" 음질이 안좋아 삭제*/
			"gwaneum","ami",
			"kukrak","musang",
			// sekisuri 20140618 "kang1","kang2","kang3","kang4",
			"han_heartsutra",
			// sekisuri 20140618 "108_7","108_8","108_9","108_10","108_11",
			//"108bow","108bow_youngin",
			"MedicineBuddha", // 여기서 부터 sosons_netcat 21번째
			"MantraOfBodhisattvaCundi",
			"Monks_of_Tibet_Healing",
			"Korean_Zen_master",
			"chant",
			"followyourheart",
			"windy_hermitage",
			"healing_music",
			"Buddhist_hymn3",
			"jeongmok_1",
			"jeongmok_2"
	};//,"han_chunsu"
	
	Resources res;// = maincon.getResources();
	int mValue;
	int mpPos=0;
	TextView mText;
	ProgressDialog mProgress;
	boolean mQuit;
	int layout;

	public DownItemAdapter(Context context, int alayout, ArrayList<DownItemList> aarSrc) {
		maincon = context;
		res = maincon.getResources();
		Inflater = (LayoutInflater)context.getSystemService(
				Context.LAYOUT_INFLATER_SERVICE);
		arSrc = aarSrc;
		layout = alayout;
	}
	

	public int getCount() {
		return arSrc.size();
	}

	public String getItem(int position) {
		return arSrc.get(position).Name;
	}

	public long getItemId(int position) {
		return position;
	}
	public boolean FileNameSearch(String strName)
	{
	    String strCompare;
		File SDCardRoot = Environment.getExternalStorageDirectory(); 
        File dir = new File(SDCardRoot + "/buddhist/");
		if(dir!=null) {
			File[] dirs = dir.listFiles();
			if(dirs!=null) {
				for(int i=0; i<dirs.length; i++) {
					
					if(dirs[i].getName().endsWith("mp3")) {
						strCompare = dirs[i].getName();
						if(strCompare.compareTo(strName) == 0) 
							return true;
					}
				}
			}
		}		
		return  false;
	}
	public String mpReNameEn(String str)
	 {
		 String strCompare = str;
		   if(strCompare.compareTo(res.getString(R.string.item_chunsu))== 0)
			   strCompare = "chunsu.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_sutra))== 0)
			   strCompare = "heartsutra.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_beopseong))== 0)
			   strCompare = "beopseong.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_hwaeom))== 0)
			   strCompare = "hwaeom.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_sinju)) == 0)
			   strCompare = "sinju.mp3";

//---------------  음질이 안좋아서 삭제
		   if(strCompare.compareTo(res.getString(R.string.item_kanmu)) == 0)
			   strCompare = "kanmu.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_bodalbomun)) == 0)
			   strCompare = "bodalbomun.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_kanja)) == 0)
			   strCompare = "kanja.mp3";	
//-----------------------------------
		   
		   if(strCompare.compareTo(res.getString(R.string.item_gwaneum)) == 0)
			   strCompare = "gwaneum.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_ami)) == 0)
			   strCompare = "ami.mp3";
		   
		   if(strCompare.compareTo(res.getString(R.string.item_kukrak)) == 0)
			   strCompare = "kukrak.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_musang)) == 0)
			   strCompare = "musang.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_kang1)) == 0)
			   strCompare = "kang1.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_kang2)) == 0)
			   strCompare = "kang2.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_kang3)) == 0)
			   strCompare = "kang3.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_kang4)) == 0)
			   strCompare = "kang4.mp3";	   
		   if(strCompare.compareTo(res.getString(R.string.item_kor_heartsutra)) == 0)
			   strCompare = "han_heartsutra.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_kor_chunsu)) == 0)
			   strCompare = "han_chunsu.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_chunji)) == 0)
			   strCompare = "chunji.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_sinmyo)) == 0)
			   strCompare = "sinmyo.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_yebull))==0)
			   strCompare = "yebull.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_prajna))==0)
			   strCompare = "prajna.mp3";

/*
 * sekisuri 20140618		   
		   if(strCompare.compareTo(res.getString(R.string.item_bows07)) == 0)
			   strCompare = "108_7.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_bows08)) == 0)
			   strCompare = "108_8.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_bows09)) == 0)
			   strCompare = "108_9.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_bows10)) == 0)
			   strCompare = "108_10.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_bows11)) == 0)
			   strCompare = "108_11.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_bows_s)) == 0)
			   strCompare = "108bow.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_bows_youngin)) == 0)
			   strCompare = "108bow_youngin.mp3";
*/		   
		   if(strCompare.compareTo(res.getString(R.string.item_medicine_buddha)) == 0)
			   strCompare = "MedicineBuddha.mp3";
		   if(strCompare.compareTo(res.getString(R.string.cundi)) == 0)
			   strCompare = "MantraOfBodhisattvaCundi.mp3";
		   if(strCompare.compareTo(res.getString(R.string.monks)) == 0)
			   strCompare = "Monks_of_Tibet_Healing.mp3";
		   if(strCompare.compareTo(res.getString(R.string.zen_master)) == 0)
			   strCompare = "Korean_Zen_master.mp3";
		   
		   if(strCompare.compareTo(res.getString(R.string.item_chant)) == 0)
			   strCompare = "chant.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_followyourheart)) == 0)
			   strCompare = "followyourheart.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_windy_hermitage)) == 0)
			   strCompare = "windy_hermitage.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_healing_music)) == 0)
			   strCompare = "healing_music.mp3";
		   if(strCompare.compareTo(res.getString(R.string.Buddhist_hymn_3)) == 0)
			   strCompare = "Buddhist_hymn3.mp3";
		   
	//	   if(strCompare.compareTo(res.getString(R.string.item_diamond)) == 0)
	//		   strCompare = "diamond_sutra.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_diamond)) == 0)
			   strCompare = "diamond_sutra.mp3";
		  
		   if(strCompare.compareTo(res.getString(R.string.item_sakyamuni)) == 0)
			   strCompare = "sakyamuni.mp3";
		   if(strCompare.compareTo(res.getString(R.string.item_guan)) == 0)
			   strCompare = "guan.mp3";
		   
		   if(strCompare.compareTo(res.getString(R.string.mp3_meditation)) == 0)
			   strCompare = "jeongmok_1.mp3";
		   if(strCompare.compareTo(res.getString(R.string.mp3_meditation_2)) == 0)
			   strCompare = "jeongmok_2.mp3";
		   return strCompare;
	 }
	// 각 항목의 뷰 생성
	public View getView(int position, View convertView, ViewGroup parent) {
		final int pos = position;
		boolean isBtnCheck;
		String strBtnCheck;

		if (convertView == null) {
			convertView = Inflater.inflate(layout, parent, false);
		}
		ImageView img = (ImageView)convertView.findViewById(R.id.img);
		img.setImageResource(arSrc.get(position).Icon);

		TextView txt = (TextView)convertView.findViewById(R.id.text);
		txt.setText(arSrc.get(position).Name);
		
		Button btn = (Button)convertView.findViewById(R.id.btn);
		//btn.setText(res.getString(R.string.item_down));
		btn.setText("Down");

	    strBtnCheck = mpReNameEn(arSrc.get(position).Name);
		isBtnCheck= FileNameSearch(strBtnCheck);
		
		if(isBtnCheck ==true)
		{
			btn.setVisibility(View.GONE);
			img.setVisibility(View.VISIBLE);		
		}
		else
		{
			img.setVisibility(View.GONE);
			btn.setVisibility(View.VISIBLE);
			
		}
		
		btn.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				mpPos = pos;
				alertDown();
			}		
		});

		return convertView;
	}
	
	void mpDownManager(int position)
	{
		switch(position)
		{
			case 0:			
				break;
			case 1:
				break;
			case 2:
				break;
			case 3:
				break;
		}
	}
	void doDownload() {
		new AccumulateTask().execute(100);
	}
	void alertDel()
	{
		new AlertDialog.Builder(maincon)
		.setTitle("삭제")
		.setMessage("삭제 할까요?")
		.setPositiveButton("예", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				mpDelete();				
			}
		})				
		.setNegativeButton("아니오", null)
		.show();
	}
	void mpDelete()
	{
		
	}
	void alertDown()
	{
		new AlertDialog.Builder(maincon)
		.setTitle(res.getString(R.string.dialog_alert))
		.setMessage(res.getString(R.string.dialog_message_down))
		.setPositiveButton(res.getString(R.string.dialog_yes), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {			
				doDownload();				
			}
		})				
		.setNegativeButton(res.getString(R.string.dialog_no), null)
		.show();
	}
	/*
	public String[]getFilesList()
	{
		String dirName ="";
		String fileList[] = null;
		String sdcardState = android.os.Environment.getExternalStorageState();
		if(sdcardState.contentEquals(android.os.Environment.MEDIA_MOUNTED))
		{
			dirName = android.os.Environment.getExternalStorageDirectory() + File.separator;
			File dir = new File(dirName);
			FilenameFilter filter = new FilenameFilter()
			{
				public boolean accept(File file,String name)
				{
					return (name.endsWith(".mp3"));
				}
			};
			filename.setText("corrent path : " + dirName);
			fileList = dir.list(filter);
			return fileList;
		}
	}
	*/
	class AccumulateTask extends AsyncTask<Integer, Integer, Integer> {
		protected void onPreExecute() {
			mValue = 0;
			mProgress = new ProgressDialog(maincon);
			mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgress.setTitle(res.getString(R.string.dialog_alert));
			mProgress.setMessage(res.getString(R.string.dialog_down));
			mProgress.setCancelable(false);
			mProgress.setProgress(0);
			mProgress.setButton(res.getString(R.string.dialog_stop), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					cancel(true);
				}
			});
			mProgress.show();
		}
		
		protected Integer doInBackground(Integer... arg0) {
			while (isCancelled() == false) { 
			//	mValue++;
				if (mValue <= 100) {
					publishProgress(mValue);
				} else {
					//String str = mValue + " ";
					//Toast.makeText(maincon, str, Toast.LENGTH_SHORT).show();
					break;
				}
				try { 
						String urlstr ="";
						if(mpPos < 10)
						{
						 	urlstr = "https://sites.google.com/site/sekisuri/";
						}
					/* 	sekisuri 20140618 //"108_7","108_8","108_9","108_10","108_11", 삭제해서 제
						else if(mpPos > 13 && mpPos < 21 )
						{
							urlstr ="https://sites.google.com/site/buddhisttext/";
						}
					*/	
						else
						{
							urlstr ="https://sites.google.com/site/sosonsnetcat/";

						}
						String mpfilestr = urlstr + mpFile[mpPos] + ".mp3";
					    URL url = new URL(mpfilestr);
					   
				        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();   
				        urlConnection.setRequestMethod("GET");   
				        urlConnection.setDoOutput(true);   			        
				        urlConnection.connect();   
				        int totalSize = urlConnection.getContentLength();   
				        int downloadedSize = 0;   
				        if(totalSize <= 0)
				        {
				        	mValue = 101;
					        Thread.sleep(50);
				        }
				        else
				        {
					        File SDCardRoot = Environment.getExternalStorageDirectory(); 
					        File path = new File(SDCardRoot + "/buddhist/");
		
					        if(! path.isDirectory()) {
					                path.mkdirs();
					          }
					       
					        File file = new File(path, mpFile[mpPos]+ ".mp3");   
					        FileOutputStream fileOutput = new FileOutputStream(file);   
					        InputStream inputStream = urlConnection.getInputStream();   
					       
				//	        int totalSize = urlConnection.getContentLength();   
				//	        int downloadedSize = 0;   
					                
					        byte[] buffer = new byte[1024];   
					        int bufferLength = 0;
					         while ( (bufferLength = inputStream.read(buffer)) > 0 ) {   
					         fileOutput.write(buffer, 0, bufferLength);   
					         downloadedSize += bufferLength;   
					             updateProgress(downloadedSize, totalSize); 
					         }
					        
					         mValue = 101;
					         fileOutput.close();  
					         Thread.sleep(50);
				         }
				        
				         } catch (InterruptedException e) {
				          e.printStackTrace();
				         }catch (MalformedURLException e) {   
				          e.printStackTrace();   
				         } catch (IOException e) {   
				          e.printStackTrace();   
				         }
				       }
			return mValue;
		}
			 public void updateProgress(int downloadedSize, int totalSize) {
				  // TODO Auto-generated method stub
				 mProgress.setProgress(100 * downloadedSize/totalSize); 
				 }

	    protected void onProgressUpdate(Integer... progress) {         
	    	mProgress.setProgress(progress[0]);     
	    //	mText.setText(Integer.toString(progress[0]));     
	    }
	    
	    protected void onPostExecute(Integer result) { 
	    	mProgress.dismiss();
	    }
	    
	    protected void onCancelled() {
			mProgress.dismiss();
	    }
	}
	

}
